<template>
  <n-drawer
    v-model:show="drawerVisible"
    width="90%"
    :trap-focus="false"
    :block-scroll="false"
    to=".drawer_container"
    :on-mask-click="closedDrawer"
    :on-esc="closedDrawer"
  >
    <n-drawer-content>
      <template #header>{{ headerTitle }}</template>
      <n-form ref="formRef" :model="form" :rules="rules" :label-width="80" label-placement="left">
        <n-grid>
          <n-form-item-gi :span="12" label="用户昵称" path="nickName">
            <n-input v-model:value="form.nickName" placeholder="" maxlength="20" />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="所属部门" path="deptId">
            <n-tree-select
              v-model:value="form.deptId"
              :cascade="false"
              filterable
              key-field="id"
              :options="treeOptions"
            />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="手机号码" path="phonenumber">
            <n-input v-model:value="form.phonenumber" placeholder="" maxlength="11" />
          </n-form-item-gi>
          <n-form-item-gi v-if="!form.userId" :span="12" label="登录账号" path="userName">
            <n-input v-model:value="form.userName" placeholder="" maxlength="20" />
          </n-form-item-gi>
          <n-form-item-gi v-if="!form.userId" :span="12" label="登录密码" path="password">
            <n-input
              v-model:value="form.password"
              type="password"
              passively-activated
              show-password-on="click"
              placeholder=""
              maxlength="20"
            />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="邮箱" path="email">
            <n-input v-model:value="form.email" placeholder="" maxlength="20" />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="用户性别" path="sex">
            <n-select v-model:value="form.sex" :options="dicts.sexOptions" />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="职位" path="postIds">
            <n-select
              v-model:value="form.postIds"
              multiple
              label-field="postName"
              value-field="postId"
              :options="postOptions"
            />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="角色" path="roleIds">
            <n-select
              v-model:value="form.roleIds"
              multiple
              label-field="roleName"
              value-field="roleId"
              :options="roleOptions"
            />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="状态" path="status">
            <n-radio-group v-model:value="form.status">
              <n-radio v-for="item in dicts.statusOptions" :key="item.value" :value="item.value">
                {{ item.label }}
              </n-radio>
            </n-radio-group>
          </n-form-item-gi>
          <n-form-item-gi :span="24" label="备注" path="remark">
            <n-input v-model:value="form.remark" type="textarea" :rows="4" placeholder="" maxlength="200" />
          </n-form-item-gi>
        </n-grid>
      </n-form>
      <template #footer>
        <n-button class="mr-3" @click="closedDrawer">取消</n-button>
        <n-button type="primary" :loading="loading" :disabled="loading" @click="save">确定</n-button>
      </template>
    </n-drawer-content>
  </n-drawer>
</template>
<script setup lang="ts">
import { treeselect } from '@/service/api/system/dept';
import { listPost } from '@/service/api/system/post';
import { listRole } from '@/service/api/system/role';
import { addUser, getUser, updateUser } from '@/service/api/system/user';
import { getDictionary } from '@/service/common';
import { formRules } from '@/utils/rule';
import type { FormInst, FormRules, TreeOption } from 'naive-ui';

// props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  deptId: {
    type: Number,
    default: 0
  },
  userId: {
    type: Number,
    default: 0
  }
});
const drawerVisible = ref(false);
watch(
  () => props.visible,
  val => {
    drawerVisible.value = val;
  },
  { immediate: true }
);
const headerTitle = computed(() => (props.userId ? '编辑' : '新增'));

const _form = {
  nickName: '',
  deptId: 0,
  phonenumber: '',
  email: '',
  userName: '',
  password: '',
  sex: '',
  status: '0',
  postIds: '',
  roleIds: '',
  remark: '',
  userId: 0
};
const form = ref<any>({ ..._form });
const rules: FormRules = {
  nickName: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
  userName: [{ required: true, message: '请输入登录账号', trigger: 'blur' }],
  password: formRules.pwd,
  postIds: [{ required: true, message: '请输选择职位', trigger: ['change', 'blur'], type: 'array' }],
  roleIds: [{ required: true, message: '请输选择角色', trigger: ['change', 'blur'], type: 'array' }]
};

// drawer 关闭方法
const emit = defineEmits(['closed', 'success']);
const closedDrawer = () => {
  form.value = { ..._form };
  emit('closed');
};

// 获取部门树
const defaultExpandedKeys = ref();
const treeOptions = ref<TreeOption[]>();
const getTreeList = async () => {
  const { data } = await treeselect();
  if (data) {
    treeOptions.value = data;
    defaultExpandedKeys.value = [data[0].id];
  }
};

// 字典值
const dicts = reactive<any>({
  sexOptions: [],
  statusOptions: []
});
watch(
  () => props.visible,
  val => {
    if (val) {
      getDictionary('sys_user_sex', dicts, 'sexOptions');
      getDictionary('sys_normal_disable', dicts, 'statusOptions');
      getTreeList();
      getRoleList();
      getPostList();
    }
  }
);

/** 获取详情 */
const getUserFun = async (userId?: number) => {
  const { data } = await getUser(userId);
  const _info = data!.user;

  if (props.userId && _info) {
    Object.keys(form.value).forEach(i => {
      if (_info[i]) form.value[i] = _info[i];
    });
    form.value.postIds = data!.postIds;
    form.value.roleIds = data!.roleIds;
  }
};
watch([() => props.userId, () => props.visible], ([userIdVal, visibleVal]) => {
  if (userIdVal && visibleVal) getUserFun(userIdVal);
});

// 提交
const formRef = ref<FormInst | null>(null);
const loading = ref<boolean>(false);
// 保存方法
const addUserFun = async (params: object) => {
  const { data } = await addUser(params);
  loading.value = false;
  if (data) {
    window.$message?.success('新增成功');
    closedDrawer();
    emit('success');
  }
};
// 编辑方法
const updateUserFun = async (params: object) => {
  const { data } = await updateUser(params);
  loading.value = false;
  if (data) {
    window.$message?.success('编辑成功');
    closedDrawer();
    emit('success');
  }
};

const save = () => {
  formRef.value?.validate(errors => {
    if (!errors) {
      loading.value = true;
      if (!form.value.deptId) form.value.deptId = props.deptId;
      if (props.userId) {
        form.value.userId = props.userId;
        updateUserFun(form.value);
      } else {
        delete form.value.userId;
        addUserFun(form.value);
      }
    } else {
      console.log(errors);
    }
  });
};

/** 获取岗位 */
const postOptions = ref();
async function getPostList() {
  const { data } = await listPost({
    tableSize: 1000,
    tableNum: 1
  });
  if (data) {
    postOptions.value = data.rows;
  }
}

/** 获取角色 */
const roleOptions = ref();
async function getRoleList() {
  const { data } = await listRole({
    tableSize: 1000,
    tableNum: 1
  });
  if (data) {
    roleOptions.value = data.rows;
  }
}
</script>
